#include <header.h>
void handler(int num){
    printf("中断退出\n");
    exit(0);
}

int main(int argc, char* argv[]){
	ARGS_CHECK(argc, 1);
    
    signal(10, handler);

    int pipe_read = open("pipe1", O_RDONLY);
	ERROR_CHECK(pipe_read, -1, "open read");
    int pipe_write = open("pipe2", O_WRONLY);
	ERROR_CHECK(pipe_write, -1, "open write");

    fd_set set;
    FD_ZERO(&set);

    pid_t pid = getpid();
    int ret1 = write(pipe_write, &pid, sizeof pid);
    ERROR_CHECK(ret1, -1, "write\n");

    pid_t peer;
    int ret2 = read(pipe_read, &peer, sizeof pid);
    ERROR_CHECK(ret2, -1, "read\n");
    
    while(1){

        FD_SET(STDIN_FILENO, &set);
        FD_SET(pipe_read, &set);

        
		int ret_select = select(10, &set, NULL, NULL, NULL);
        ERROR_CHECK(ret_select, -1, NULL);

		if(ret_select == 0){
			printf("超时退出");
			exit(0);
		}


        // 键盘输入
        if(FD_ISSET(STDIN_FILENO, &set)){
            char buf[60] = {0};
            bzero(buf, sizeof(buf));
            read(STDIN_FILENO, buf, sizeof(buf));
            write(pipe_write, buf, sizeof(buf));

            if(strcmp(buf, "1\n") == 0){
                // TODO kill 10
                kill(peer, 10);
                printf("键盘退出\n");
                break;
            }
        }

        // 管道读入
        if(FD_ISSET(pipe_read, &set)){
            char buf[60] = {0};
            bzero(buf, sizeof(buf));
            int res = read(pipe_read, buf, sizeof(buf));
            if(res == 0){
                printf("对端关闭了管道 \n");
                break;
            }
            printf("A: %s \n", buf);
        }
    }

    close(pipe_read);
    close(pipe_write);

    return 0;	
}